package com.zhl.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.zhl.dao.DeptDao;
import com.zhl.model.Dept;
import com.zhl.service.DeptService;
import com.sun.xml.internal.bind.v2.model.core.ID;

import java.util.*;

public class DeptServiceImpl implements DeptService {

    DeptDao deptDao = new DeptDao();

    @Override
    public List<Dept> findDepts() {
        return deptDao.fingAll();
    }

    @Override
    public Dept findDeptByName(String DeptName) {
        return deptDao.findByDept(DeptName);
    }

    @Override
    public Dept findDeptById(Integer id) {
        return deptDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findDeptInfo() {

        List<Map<String,Object>> results = new ArrayList<>();

        List<Map<String, Object>> deptList = deptDao.findDeptInfo();
        Map<String,Object> map;
        Set<String> deptIds = new HashSet<>();

        for (Map<String,Object> dept:deptList) {
            map = new HashMap<>();
            String deptId = dept.get("id").toString();
            String deptName = dept.get("name").toString();
            if (!deptIds.contains(deptId)){
                map.put("deptId",deptId);
                map.put("deptName",deptName);
                results.add(map);
                deptIds.add(deptId);
            }
        }

        for (Map<String,Object> dept:results) {
            List<Map<String, Object>> userList = new ArrayList<>();
            String deptId = dept.get("deptId").toString();
            for (Map<String,Object> user:deptList) {
                String deptId2 = user.get("id").toString();
                if (deptId.equals(deptId2)){
                    if (user.get("uId") != null){
                        userList.add(user);
                    }
                }
            }
            dept.put("userList",userList);
            dept.put("count",userList.size());
        }
        return results;
    }
}
